import type { RouteRecordRaw } from 'vue-router'

const modules = import.meta.glob('../pages/**/*.vue')

interface Route {
  path: string
  name: string
  component: () => Promise<any>
  meta?: {
    title?: string
  }
}

function formatPath(path: string): string {
  return path
    .replace(/^\.\.\/pages/, '')
    .replace(/\.vue$/, '')
    .replace(/index$/, '')
    .replace(/\[(\w+)\]/g, ':$1')
    .replace(/\/+/g, '/')
    || '/'
}

function formatName(path: string): string {
  return path
    .replace(/^\.\.\/pages\//, '')
    .replace(/\.vue$/, '')
    .replace(/\//g, '-')
    .replace(/\[(\w+)\]/g, '$1')
    .toLowerCase()
}

export function generateRoutes(): RouteRecordRaw[] {
  const routes: Route[] = []

  for (const path in modules) {
    const name = formatName(path)
    const routePath = formatPath(path)

    routes.push({
      path: routePath,
      name,
      component: modules[path],
      meta: {
        title: name
      }
    })
  }

  return routes
}